//
//  ICMOwnerCarInfoEditViewController.m
//  ICrEAM
//
//  Created by xphone on 16/11/22.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMOwnerCarInfoEditViewController.h"
#import "ICMHeaderView.h"
#import "ICMOwnerInfoEditView.h"
#import "ICMBottomBarView.h"
#import "ICMCarInfoEditView.h"
#import "SyncVehicleInfoAction.h"
#import "SyncVehicleInfoResponse.h"

@interface ICMOwnerCarInfoEditViewController ()<ICMHeaderViewDelegate,ICMBottomBarViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) ICMHeaderView *headerView;
@property (nonatomic, strong) TPKeyboardAvoidingScrollView *bigScrollView;
@property (nonatomic, strong) ICMOwnerInfoEditView *ownerEditView;
@property (nonatomic, strong) ICMCarInfoEditView *carEditView;
@property (nonatomic, strong) ICMBottomBarView *bottomBarView;

//记录保修结束里程
@property (nonatomic, strong) NSString *oldMi;

@end

@implementation ICMOwnerCarInfoEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackgroundColor_HeaderBlue;
    [self setupHeadView];
    [self.view addSubview:self.bigScrollView];
    [self.bigScrollView addSubview:self.ownerEditView];
    [self.bigScrollView addSubview:self.carEditView];
    
    self.oldMi = self.carModel.guaranteeEndMillions;
    
    [self setupBottomView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentVC:) name:@"popoverSelectionView" object:nil];
}

- (void)presentVC:(NSNotification *)notification {

    [self presentViewController:[notification object] animated:YES completion:nil];
    
}

#pragma mark 配置headView
- (void)setupHeadView
{
    self.headerView = [ICMHeaderView createHeaderViewWithFrame:CGRectMake(0, 0, ScreenWidth, 40) andTitles:@[@"车主信息",@"车辆信息"] andType:@"0"];
    self.headerView.delegate = self;
    [self.view addSubview:self.headerView];
}

#pragma mark 配置bottomView
- (void)setupBottomView
{
    _bottomBarView = [ICMBottomBarView createBottomBarViewWithTitles:@[@"保 存"] normalImages:@[[UIImage imageNamed:@"btn_save"]] seletedImages:nil andFrame:CGRectMake(0, ScreenHeight-70-64, ScreenWidth, 70)];
    _bottomBarView.delegate = self;
    [self.view addSubview:_bottomBarView];
}

#pragma mark ICMHeaderViewDelegate
- (void)headerViewDidSelectedButtonAtIndex:(NSInteger)index
{
    if(index == 0)
    {
        [self.bigScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    if(index == 1)
    {
        [self.bigScrollView setContentOffset:CGPointMake(ScreenWidth, 0) animated:NO];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(self.bigScrollView.contentOffset.x == 0)
    {
        self.headerView.selectedIndex = 0;
    }
    if(self.bigScrollView.contentOffset.x == ScreenWidth)
    {
        self.headerView.selectedIndex = 1;
    }
}

- (void)bottomBarViewDidSelectIndex:(NSInteger)index{

    if (index == 0) {
        //保存
        [self startToSaveOwnerCarInfoToServer];
    }
}

#pragma mark 获取所有页面当中的数据保存到model当中
- (void)getAllDataModels{
    //去空格
    NSString *OWNER_MOBILE = self.personerModel.phoneNum;
    NSString *DELIVERER_MOBILE = self.personerModel.CONTACTOR_MOBILE;
    self.personerModel.phoneNum = [ICrEAMTool trimWhitespace:OWNER_MOBILE];
    self.personerModel.CONTACTOR_MOBILE = [ICrEAMTool trimWhitespace:DELIVERER_MOBILE];
    
    if([self.personerModel.ownerType isEqualToString:@"11901002"]){
        self.personerModel.ownerName = [ICrEAMTool trimWhitespace:self.personerModel.ownerName];
        self.personerModel.CONTACTOR_NAME = [ICrEAMTool trimWhitespace:self.personerModel.CONTACTOR_NAME];
    }

    //self.personerModel = [[ICMPersonerModel alloc] init];
    [self.personerModel setupPersonerModelWithOwnerInfoEditView:self.ownerEditView];
    
    //self.carModel = [[ICMCarModel alloc] init];
    [self.carModel setupCarModelWithCarInfoEditView:self.carEditView WithOwnerInfoEditView:self.ownerEditView];
}

#pragma mark 构造保存车主车辆接口数据
- (NSMutableDictionary *)setupSaveOwnerCarData{
    
    [self getAllDataModels];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    
    NSDictionary *perInfoModelDic = [self.personerModel yy_modelToJSONObject];
    NSDictionary *carModelDic = [self.carModel yy_modelToJSONObject];
    
    NSArray *perArray = [[NSArray alloc] initWithObjects:perInfoModelDic, nil];
    NSArray *carArray = [[NSArray alloc] initWithObjects:carModelDic, nil];
    
    [dataDic setObject:perArray forKey:@"TM_OWNER"];
    [dataDic setObject:carArray forKey:@"TM_VEHICLE"];
    return dataDic;
}

#pragma mark 表单 check
- (BOOL)checkFormData
{
    
    if([self.personerModel.ownerType isEqualToString:@"11901002"]){
        if([ICrEAMTool isVaildRealName:self.personerModel.ownerName] == NO ){
            
            [self.view showString:@"车主姓名有误，请修改后保存！" forSeconds:1.5];
            return NO;
        }
    }
    if([self.personerModel.ownerType isEqualToString:@"11901001"]){
        if([ICrEAMTool isVaildCompanyName:self.personerModel.ownerName] == NO ){
            
            [self.view showString:@"公司名称有误，请修改后保存！" forSeconds:1.5];
            return NO;
        }
    }
    if([ICrEAMTool validateMobile:self.personerModel.phoneNum] == NO ){
        
        [self.view showString:@"车主手机号有误，请修改后保存！" forSeconds:1.5];
        return NO;
    }
    
    if([self.personerModel.cerType isEqualToString:@"12391001"]){
        
        if([ICrEAMTool judgeIdentityStringValid:self.personerModel.cerNum] == NO ){
            
            [self.view showString:@"证件号有误，请修改后保存！" forSeconds:1.5];
            return NO;
        }

    
    }
    if([self.personerModel.cerType isEqualToString:@"12391007"]){
        if([ICrEAMTool isValidEntpCode:self.personerModel.cerNum] == NO ){
            
            [self.view showString:@"证件号有误，请修改后保存！" forSeconds:1.5];
            return NO;
        }

    }

    if(!self.personerModel.phoneNum || [self.personerModel.phoneNum isEqualToString:@""])
    {
        [self.view showString:@"手机号码为空，请检查!" forSeconds:1.5f];
        return NO;
    }
//    if(self.personerModel.phoneNum && (self.personerModel.phoneNum.length != 11 || ![self isPureInt:self.personerModel.phoneNum]))
//    {
//        [self.view showString:@"手机号码有误，请检查!" forSeconds:1.5f];
//        return NO;
//    }
    
//    if(![ICrEAMTool isPhoneNumber:self.personerModel.phoneNum])
//    {
//        [self.view showString:@"手机号码有误，请检查!" forSeconds:1.5f];
//        return NO;
//    }
    
    if(!self.carModel.guaranteeEndMillions || (self.carModel.guaranteeEndMillions && ![self isPureFloat:self.carModel.guaranteeEndMillions]))
    {
        [self.view showString:@"保修结束里程有误，请检查!" forSeconds:1.5f];
        return NO;
    }
    if(self.carModel.guaranteeEndMillions && [self.carModel.guaranteeEndMillions floatValue] < [self.oldMi floatValue])
    {
        [self.view showString:@"保修结束里程不能小于原来的保修结束里程，请检查!" forSeconds:1.5f];
        return NO;
    }
    if(self.ownerEditView.ownerVerTypeView.contentText && [self.ownerEditView.ownerVerTypeView.contentText isEqualToString:@"居民身份证"] && ![ICrEAMTool judgeIdentityStringValid:self.personerModel.cerNum])
    {
        [self.view showString:@"身份证号码有误，请检查!" forSeconds:1.5f];
        return NO;
    }
    
    return YES;
}

#pragma mark 保存车主车辆接口
- (void)startToSaveOwnerCarInfoToServer{
    
    
    NSMutableDictionary *paraDic = [self setupSaveOwnerCarData];
    
    if(![self checkFormData])
    {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/updateOwnerAndVehicleInfo"];
    [[[ICMRequestManager alloc]init]startPostRequestWithURL:url parameters:paraDic inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if (!failText) {
            //保存成功
            [self.view showString:@"保存成功!" forSeconds:1.5f];
            self.oldMi = self.carModel.guaranteeEndMillions;
            //            self.isSave = YES;
            //            self.appointmentNumber = data[@"BOOKING_ORDER_NO"];
        }else{
            //保存失败
            [self.view showString:@"保存失败!" forSeconds:1.5f];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (TPKeyboardAvoidingScrollView *)bigScrollView
{
    if(!_bigScrollView)
    {
        _bigScrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight)];
        _bigScrollView.contentSize = CGSizeMake(ScreenWidth*2, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight);
        _bigScrollView.pagingEnabled = YES;
        _bigScrollView.delegate = self;
    }
    _bigScrollView.backgroundColor = [UIColor clearColor];
    return _bigScrollView;
}

- (ICMOwnerInfoEditView *)ownerEditView
{
    if(!_ownerEditView)
    {
        _ownerEditView = [[ICMOwnerInfoEditView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight)];
        [self getAllServerNameAndCode];
        
    }
    return _ownerEditView;
}

- (ICMCarInfoEditView *)carEditView
{
    if(!_carEditView)
    {
        _carEditView = [[ICMCarInfoEditView alloc] initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight)];
        _carEditView.delegate=self;
    }
    return _carEditView;
}
#pragma mark 同步车辆信息
-(void)syncVehicleInfoWithVin:(NSString *)vin{
    
    SyncVehicleInfoAction *action=[[SyncVehicleInfoAction alloc]init];
    action.vin=vin;
    [self requestDataWithAction:action haveHud:YES showError:NO success:^(__kindof YTKBaseRequest *request) {
        NSArray *arr=request.responseJSONObject[@"TM_VEHICLE"];
        if (IsArrEmpty(arr)) {
            [self showText:@"车主车辆信息同步失败！"];
            return ;
        }
        
        NSDictionary *vheicleDic=arr[0];
        SyncVehicleInfoResponse *respose=[SyncVehicleInfoResponse mj_objectWithKeyValues:vheicleDic];
        if (IsStrEmpty(respose.VIN)) {
            [self showText:@"车主车辆信息同步失败！"];
            return;
        }else{
            [self showText:@"车主车辆信息同步成功！"];
        }
        self.personerModel.ownerName=respose.OWNER_NAME;
        self.personerModel.gender=respose.GENDER;
        self.personerModel.cerType=respose.CT_CODE;
        self.personerModel.cerNum=respose.CERTIFICATE_NO;
        self.personerModel.address=respose.ADDRESS;
        self.personerModel.phoneNum=respose.CONTACTOR_MOBILE;
        self.carModel.vinNum=respose.VIN;
        self.carModel.carKei=respose.SERIES_CODE;
        SeriesModel *seriesModel=[ICrEAMTool querySeriesModelWithSerieCode:respose.SERIES_CODE];
        self.carModel.carKeiName=seriesModel.SERIES_NAME;
        self.carModel.carType=respose.MODEL_CODE;
        
        self.carModel.brandName=[ICrEAMTool isVW]?@"大众":@"斯柯达";
        self.carModel.brand=[ICrEAMTool isVW]?@"VW":@"SKODA";;
        TMModel *model=[ICrEAMTool queryTMModelWithSerieCode:respose.SERIES_CODE ModelCode:respose.MODEL_CODE];
        self.carModel.carTypeName=model.MODEL_NAME;
        if (!IsStrEmpty(respose.SALE_DATE)) {
            self.carModel.parchaseDate=respose.SALE_DATE;
        }
        self.carEditView.carModel=self.carModel;
        self.ownerEditView.personerModel=self.personerModel;
        self.super_owner_no = self.personerModel.OWNER_NO;
        self.super_VIN = self.carModel.vinNum;
        [self.carEditView setupData];
        [self.ownerEditView setupData];
        
        
    } failure:^(__kindof YTKBaseRequest *request) {
        [self showText:@"车主车辆信息同步失败！"];
    }];
    
}
- (void)setPersonerModel:(ICMPersonerModel *)personerModel
{
    _personerModel = personerModel;
    self.ownerEditView.personerModel = _personerModel;
    self.super_owner_no = self.personerModel.OWNER_NO;
    [self.ownerEditView setupData];
}

- (void)setCarModel:(ICMCarModel *)carModel
{
    _carModel = carModel;
    self.carEditView.carModel = _carModel;
    self.super_VIN=self.carModel.vinNum;
    [self.carEditView setupData];
}

#pragma mark 重新设置专属服务顾问
- (void)resetServerWithCode:(NSString *)code WithName:(NSString *)name
{
    self.ownerEditView.personerModel.adviserCode = code;
    self.ownerEditView.personerModel.adviserName = name;
    [self.ownerEditView setupData];
}

#pragma mark 工具
#pragma mark 浮点数判断
- (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

#pragma mark 整型判断
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

#pragma mark 获得所有的服务顾问姓名和编码
- (void)getAllServerNameAndCode{
    [[[ICMRequestManager alloc]init]startGetRequestWithURL:@"/INFO_ICREAM_WEB/App/queryServiceAdvisor" parameters:nil inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        NSLog(@"%@",data);
        if (data) {
            NSArray *allServers = data[@"TM_USER"];
            NSMutableArray *nameArray = [[NSMutableArray alloc] init];
            NSMutableArray *noArray = [[NSMutableArray alloc] init];
            if ([allServers isKindOfClass:[NSArray class]]) {
                for (NSDictionary *server in allServers) {
                    [nameArray addObject:server[@"EMPLOYEE_NAME"]];
                    [noArray addObject:server[@"EMPLOYEE_NO"]];
                }
                [self.ownerEditView getAllServerNameAndCodeWithNoArray:noArray WithNameArray:nameArray];
            }
        }
    }];
}

@end
